package com.gopay.scheduler.job;

import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.cps.dao.aggregatepayment.ApCustInfoQueryDAO;
import com.gopay.common.domain.aggregatepayment.ApCustInfo;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.dao.CustCorpInfoQueryDAO;
import com.gopay.cron.web.util.RemoteServiceUtil;
import com.gopay.remote.cps.mail.MailRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lij-jiang
 * @ClassName: APMerModifyNotifyJob.java
 * @Description: 聚合支付-平安银行入驻商户资料变更通知 AP:Aggregate Payment
 * @date 2018年01月06日 11:17
 */
public class APMerModifyNotifyJob extends GopayBaseJob {

    private final Logger logger = LoggerFactory.getLogger(APMerModifyNotifyJob.class);

    @Value("#{webProperties['remotenotify.cps.mail.url']}")
    private String notifyEmailUrl;

    @Value("#{webProperties['portal.url']}")
    private String portalUrl;

    @Value("#{webProperties['apMerModifyNotifyEmail']}")
    private String apMerModifyNotifyEmail;

    @Resource(name = "custCorpInfoQueryDao")
    private CustCorpInfoQueryDAO custCorpInfoQueryDAO;

    @Resource(name = "apCustInfoQueryDAO")
    private ApCustInfoQueryDAO apCustInfoQueryDAO;

    @Override
    protected void doJobInternal() {
        logger.error("--聚合支付-平安银行入驻商户资料变更通知--start--");
        // 1 为商户入驻审核通过
        String status = "1";
        try {
            // 查询平安银行渠道入驻并且审核通过商户
            List<ApCustInfo> apCustInfos = apCustInfoQueryDAO.getInfoByAccessChannelAndStatus(BisBankInterfaceChannel._25.value, status);

            if (apCustInfos != null && !apCustInfos.isEmpty()) {
                // 保存要对比的商户信息 corpName(企业名称)、businessLicenseNo(营业执照代码)、legalPersonName(法人姓名)
                Map<String, String> apCustInfoMap = new HashMap<>(apCustInfos.size());
                List<Object> custIds = new ArrayList<>();

                for (ApCustInfo apCustInfo : apCustInfos) {
                    apCustInfoMap.put(apCustInfo.getCustId(), apCustInfo.getMerChantName()
                            + apCustInfo.getBusinessLicenseNo() + apCustInfo.getLegalPersonName()
                            + apCustInfo.getLegalPersonMob());
                    custIds.add(apCustInfo.getCustId());
                }

                // 查出对应的企业信息
                List<CustCorpInfo> custCorpInfoList = custCorpInfoQueryDAO.getInfoByCustIds(custIds);

                setMsgList(custCorpInfoList, apCustInfoMap);
            }
        } catch (Exception e) {
            logger.error("聚合支付-平安银行入驻商户资料变更通知失败：" + e.getMessage());
        }

        logger.error("--聚合支付-平安银行入驻商户资料变更通知--end--");
    }

    private void setMsgList(List<CustCorpInfo> custCorpInfoList, Map<String, String> apCustInfoMap) throws GopayException {
        List<String> sendMsg = new ArrayList<>();
        for (CustCorpInfo custCorpInfo : custCorpInfoList) {
            String value = custCorpInfo.getCorpName() + custCorpInfo.getBusinessLicenseNo()
                    + custCorpInfo.getLegalPersonName() + custCorpInfo.getLegalPersonMobile();
            if (!value.equals(apCustInfoMap.get(custCorpInfo.getCustId()))) {
                StringBuilder msg = new StringBuilder();
                msg.append("客户ID：" + custCorpInfo.getCustId());
                msg.append(" 客户名称：" + custCorpInfo.getCorpName());
                msg.append(" 客户邮箱：" + custCorpInfo.getEmail());
                msg.append(" 法人手机号：" + custCorpInfo.getLegalPersonMobile());
                sendMsg.add(msg.toString());
            }
        }
        if(sendMsg.size() > 0) {
            setSendInfo(sendMsg);
        }

    }

    private void setSendInfo(List<String> corpInfoLists) throws GopayException {
        Send send = new Send();
        // 收件人
        send.setReceivers(apMerModifyNotifyEmail);
        send.setTemplate("apMerModifyInfo");
        send.setLevel(MailLevel.MID);
        Map<String, Object> json = new HashMap<String, Object>(2);
        json.put("portalUrl", portalUrl);
        json.put("corpInfoLists", corpInfoLists);
        send.setContent(JSONObject.fromObject(json).toString());
        sendEmail(send);
    }

    private void sendEmail(Send send) {
        try {
            MailRemoteService service =
                    (MailRemoteService) RemoteServiceUtil.getRemoteService(MailRemoteService.class, notifyEmailUrl);
            service.addMailTask(send);
        } catch (GopayException e) {
            logger.error("聚合支付-平安银行入驻商户资料变更通知发送邮件异常：", e);
        }
    }
}
